package com.newture.lxz.errors;

import com.newture.lxz.controller.helper.Result;
import com.newture.lxz.i18n.I18nTranslator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author xiao.hu
 * @date 2021-09-25
 * @apiNote
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = AppException.class)
    @ResponseBody
    public Result bizExceptionHandler(HttpServletRequest req, AppException e){
        logger.error("bizExceptionHandler：{}", e.getDevelopmentDetails());
        return Result.failure(e.getErrorCode(), I18nTranslator.get(e.getErrorCode()));
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, NullPointerException e){
        logger.error("NullPointerException: {}", e);
        return Result.failure(Errors.INTERNAL_ERROR.name());
    }


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, Exception e){
        logger.error("Unknown exception: {}", e);
        return Result.failure(Errors.UNKNOWN_ERROR.name());
    }
}
